//
//  UIColor+utils.m
//  helper
//
//  Created by huangyi on 12-10-29.
//  Copyright (c) 2012年 huangyi. All rights reserved.
//

#import "UIColor+utils.h"
#import "NSString+path.h"

@implementation UIColor (utils)

+(UIColor*)randomColor;{
    int red=arc4random()%256;
    int green=arc4random()%256;
    int blue=arc4random()%256;
    return UIColorFromRGB(red, green, blue);
}

-(UIColor*)invertedColor{
    CGFloat h=0;
    CGFloat s=0;
    CGFloat b=0;
    CGFloat a=0;
    [self getHue:&h saturation:&s brightness:&b alpha:&a];
    int d=h*360;
    d=(d+180)%360;
    h=d/360.0;
    return [UIColor colorWithHue:h saturation:s brightness:b alpha:a];
}

@end

UIColor* UIColorFromString(NSString* str){
    NSString *color=str;
    NSString *alpha=@"100";
    NSArray *args=[str componentsSeparatedByString:@"@"];
    if (args.count==2) {
        color=[args objectAtIndex:0];
        alpha=[args objectAtIndex:1];
    }
    color=color.lowercaseString;
    static NSDictionary *colorTable=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        colorTable=[NSDictionary dictionaryWithContentsOfFile:@"colors.xml".mediaPath];
    });
    if (color.length==0) {
        return [UIColor cyanColor];
    }
    if ([color isEqualToString:@"clear"]) {
        return [UIColor clearColor];
    }
    if ([color hasPrefix:@"#"]) {
        color=[color substringFromIndex:1];
    }
    NSString *hexString=colorTable[color];
    if (hexString==nil) {
        hexString=color;
    }
    NSScanner *scanner = [NSScanner scannerWithString:hexString];
    unsigned int hex;
    if (![scanner scanHexInt:&hex]){
        return [UIColor cyanColor];
    }else{
        float a=alpha.floatValue/100;
        return UIColorFromHEXA(hex,a);
    }
}

UIColor* UIColorFromRGBA(int red,int green,int blue,float alpha){
	return [UIColor colorWithRed:(float)red/255 green:(float)green/255 blue:(float)blue/255 alpha:alpha];
}

UIColor* UIColorFromRGB(int red,int green,int blue){
	float alpha=1.0;
	return UIColorFromRGBA(red, green, blue, alpha);
}

UIColor* UIColorFromHEXA(int hex,float alpha){
	float red=(hex&0xFF0000)>>16;
	float green=(hex&0xFF00)>>8;
	float blue=(hex&0xFF);
	return UIColorFromRGBA(red, green, blue, alpha);
}

UIColor* UIColorFromHEX(int hex){
	float red=(hex&0xFF0000)>>16;
	float green=(hex&0xFF00)>>8;
	float blue=(hex&0xFF);
	float alpha=1.0;
	return UIColorFromRGBA(red, green, blue, alpha);
}

UIColor* UIColorFromGrayscale(float grayscale){
    return UIColorFromRGB(grayscale*255, grayscale*255, grayscale*255);
}

